package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.beans.Person;
import com.example.chuntiao.cophook.mytools.MyApp;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.ConnectException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LogInActivity extends BaseActivity {

    ProgressBar progressBar;
    MyApp myApp;
    EditText text_id;
    EditText text_passwd;
    AlertDialog alertDialog;
    Intent intent;
    Person me;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);


        myApp = (MyApp) getApplication();
        progressBar = (ProgressBar) findViewById(R.id.pro_bar_login);
        Button btn_login = (Button) findViewById(R.id.btn_login);
        Button btn_signUP = (Button) findViewById(R.id.btn_signUp);
        text_id = (EditText) findViewById(R.id.edit_id);

        text_passwd = (EditText) findViewById(R.id.edit_passwd);
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] strings = new String[2];
                strings[0] = text_id.getText().toString();
                strings[1] = text_passwd.getText().toString();
                if (!strings[0].equals("") && !strings[1].equals(""))
                    new LoginTask().execute(strings);
            }
        });
        btn_signUP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LogInActivity.this, SignUpActivity.class);
                startActivity(intent);
            }
        });

        alertDialog = new AlertDialog.Builder(LogInActivity.this)
                .setTitle("Sorry")
                .setMessage("登录失败")
                .setPositiveButton("确定", null)
                .create();

        CoordinatorLayout layout = (CoordinatorLayout) findViewById(R.id.coordinator);
        addLayoutListener(layout, btn_login);
    }


    class LoginTask extends AsyncTask<String, Void, Boolean> {
        ProgressDialog dialog;
        String toBeId;
        String toBePasswd;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(LogInActivity.this, "chulizhuong", "正在登录");
        }

        @Override
        protected Boolean doInBackground(String... params) {


            toBeId = params[0];
            toBePasswd = params[1];
            OkHttpClient client = myApp.getClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("uid", params[0])
                    .add("passwd", params[1])
                    .build();

            Request request = new Request.Builder()
                    .url(MyApp.HOST_S_URL + "LogIn")
                    .post(requestBody)
                    .build();
            Response response = null;
            String jsonStr;

            try {
                response = client.newCall(request).execute();

                jsonStr = response.body().string();


            } catch (ConnectException e) {
                alertDialog.setMessage("连接服务器失败，请检查网络");
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }


            if (Boolean.parseBoolean(response.header("success"))) {
                me = new Gson().fromJson(jsonStr, Person.class);
                intent = new Intent();
                intent.putExtra("uname", me.getName());
                intent.putExtra("uid", me.getUid());
                intent.putExtra("phone1", me.getPhone1());
                intent.putExtra("img_ver", me.getImgVer());
                intent.putExtra("locate", me.getLocate());
                intent.putExtra("phone2", me.getPhone2());

                SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                editor.putString("uid", params[0]);
                editor.putString("passwd", params[1]);
                editor.putString("uname", me.getName());
                editor.putString("phone2", me.getPhone2());
                editor.putString("phone1", me.getPhone1());
                editor.putString("locate", me.getLocate());

                editor.putBoolean("logedin", true);
                editor.putInt("img_ver", me.getImgVer());
                myApp.setUid(toBeId);
                myApp.setPasswd(toBePasswd);
                myApp.setUname(me.getName());
                myApp.setImgVer(me.getImgVer());
                myApp.setPhone1(me.getPhone1());
                myApp.setPhone2(me.getPhone2());
                myApp.setLocate(me.getLocate());

                synchronized (myApp.getLookObj()) {
                    myApp.setLogedIn(true);
                    myApp.setLastLogIn(System.currentTimeMillis());
                    editor.commit();
                }
                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                alertDialog = null;
                dialog.dismiss();
                setResult(RESULT_OK, intent);
                LogInActivity.this.finish();
            } else {
                dialog.dismiss();
                alertDialog.show();
            }

        }
    }

    public void addLayoutListener(final View main, final View scroll) {
        main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                main.getWindowVisibleDisplayFrame(rect);
                int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
                if (mainInvisibleHeight > 250) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                    main.scrollTo(0, srollHeight);
                } else {
                    main.scrollTo(0, 0);
                }
            }
        });
    }

}
